<?php
/**
 * Created by PhpStorm.
 * User: LENOVO
 * Date: 2018/8/6
 * Time: 22:39
 */

namespace app\wx\controller;


use app\wx\WxConfig;


class WxPublicNumber extends WxConfig
{
  public function responseMsg()
  {
    //get post data, May be due to the different environments
    $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
    //extract post data
    if (empty($postStr))
      exit("");

    /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
       the best way is to check the validity of xml by yourself */
    libxml_disable_entity_loader(true);
    $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
    $fromUsername = $postObj->FromUserName;
    $toUsername = $postObj->ToUserName;
    $time = time();
    $keyword = trim($postObj->Content);
    $msgtype = 'text'; //消息类型：文本
    $textTp1sys = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                </xml>";
    $textTpl2sys = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <ArticleCount><![CDATA[%s]]></ArticleCount>
                            <Articles>
                                <item>
                                    <Title><![CDATA[%s]]></Title>
                                    <Description><![CDATA[%s]]></Description>
                                    <PicUrl><![CDATA[%s]]></PicUrl>
                                    <Url><![CDATA[%s]]></Url>
                                </item>
                            </Articles>
                            </xml>";
    //点击菜单拉取消息时的事件推送
    /*
     * 1、click：点击推事件
     * 用户点击click类型按钮后，微信服务器会通过消息接口推送消息类型为event的结构给开发者（参考消息接口指南）
     * 并且带上按钮中开发者填写的key值，开发者可以通过自定义的key值与用户进行交互；
     */
    if ($postObj->MsgType == 'event' && $postObj->Event == 'CLICK') {
      $keyword = trim($postObj->EventKey);
    }

    /*系统关注,回复*/
    if ($postObj->MsgType == 'event') {
      if ($postObj->Event == 'subscribe') { //如果是订阅事件
        $sys = M('wx_sys')->where("status=1")->find();
        if ($sys) {
          $keyw = $sys['key'];
          if ($sys['type'] == 1) {
            $wx_text = M('wx_text')->where("keyword like '%$keyw%'")->find();
            if ($wx_text) {
              $contentStr = $wx_text['text'];
              $resultStr = sprintf($textTp1sys, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
              echo $resultStr;
              exit();
            }
          } else {
            $wx_img = M('wx_img')->where("keyword like '%$keyword%'")->find();
            if ($wx_img) {
              $resultStr = sprintf($textTpl2sys, $fromUsername, $toUsername, $time, 'news', '1', $wx_img['title'], $wx_img['desc']
                  , $wx_img['pic'], $wx_img['url']);
              exit($resultStr);
            }
          }
        }
      }
    }
    if (empty($keyword))
      exit("Input something...");
    // 图文回复
    $wx_img = M('wx_img')->where("keyword like '%$keyword%'")->find();
    if ($wx_img) {
      $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <ArticleCount><![CDATA[%s]]></ArticleCount>
                                <Articles>
                                    <item>
                                        <Title><![CDATA[%s]]></Title>
                                        <Description><![CDATA[%s]]></Description>
                                        <PicUrl><![CDATA[%s]]></PicUrl>
                                        <Url><![CDATA[%s]]></Url>
                                    </item>
                                </Articles>
                                </xml>";
      $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'news', '1', $wx_img['title'], $wx_img['desc']
          , $wx_img['pic'], $wx_img['url']);
      exit($resultStr);
    }

    // 文本回复
    $wx_text = M('wx_text')->where("keyword like '%$keyword%'")->find();
    if ($wx_text) {
      $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                <FuncFlag>0</FuncFlag>
                                </xml>";
      $contentStr = $wx_text['text'];
      $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);
      exit($resultStr);
    }

    // 其他文本回复
    $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                <FuncFlag>0</FuncFlag>
                                </xml>";
    $contentStr = '欢迎来到TPshop商城!';
    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);
    exit($resultStr);
  }

  public function definedItem()
  {
    //创建微信菜单
    //目前微信接口的调用方式都是通过 curl post/get
    header('content-type:text/html;charset=utf-8');
    $access_token = $this->getWxAccessToken();
    $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $access_token;
    $data =
        '{
  "button": [
    {
      "name": "找房",
      "sub_button": [
        {
          "type": "view",
          "name": "首页",
          "url": "https://www.linqinghu.cn/ruixiang/index.html"
        },
        {
          "type": "view",
          "name": "二手房",
          "url": "https://www.linqinghu.cn/ruixiang/findHouse/houseList.html?label=二手房"
        },
        {
          "type": "view",
          "name": "租房",
          "url": "https://www.linqinghu.cn/ruixiang/findHouse/houseList.html?label=租房"
        },
        {
          "type": "view",
          "name": "新房",
          "url": "https://www.linqinghu.cn/ruixiang/findHouse/houseList.html?label=租房"
        }
      ]
    },
    {
      "name": "委托",
      "sub_button": [
        {
          "type": "view",
          "name": "租房登记",
          "url": "https://www.linqinghu.cn/ruixiang/weituo/rentingRegester.html"
        },
        {
          "type": "view",
          "name": "买房登记",
          "url": "https://www.linqinghu.cn/ruixiang/weituo/buyHouseRegester.html"
        },
        {
          "type": "view",
          "name": "有房出售",
          "url": "https://www.linqinghu.cn/ruixiang/weituo/haveHouseSell.html"
        },
        {
          "type": "view",
          "name": "有房出租",
          "url": "https://www.linqinghu.cn/ruixiang/weituo/houseToLet.html"
        }
      ]
    },
    {
      "name": "联系",
      "sub_button": [
        {
          "type": "click",
          "name": "电话",
          "key": "phonenumber"
        },
        {
          "type": "view",
          "name": "一键关注",
          "url": "https://mp.weixin.qq.com/s?__biz=Mzg2MzAwMDEzNg==&mid=100000010&idx=1&sn=7e5cb5de3aff73925b5ca6f82ee562ea&scene=19#wechat_redirect"
        },
        {
          "type": "view",
          "name": "公司",
          "url": "https://www.linqinghu.cn/ruixiang/about/company.html"
        },
        {
          "type": "view",
          "name": "门店",
          "url": "https://www.linqinghu.cn/ruixiang/about/store.html"
        },
        {
          "type": "view",
          "name": "房贷计算",
          "url": "https://tool.fooww.com/calculator/mobile/?themeColor=3492e9"
        }
      ]
    }
  ]
}';
    return $this->_request('post', $url, $data);
//    $result_obj= json_encode($this->_request('post', $url, $menu));
//    if ($result_obj->errcode == 0) {
//      return '1111';
//    } else {
//      echo $result_obj->errmsg, '<br>';
//      return false;
//    }
  }

}